import { Card, Table, Button, Space, Row, Col, Statistic, Select } from '@/utils/antd-imports';
import { FilePdfOutlined, FileExcelOutlined, BarChartOutlined, PieChartOutlined, LineChartOutlined } from '@/utils/icons';
import { useState, useEffect } from 'react';


import DatePicker from 'antd/es/date-picker';







import { Column, Pie, Line } from '@ant-design/charts';

const { RangePicker } = DatePicker;
const { Option } = Select;

const reportData = [
  { id: 1, year: 2023, month: 1, monthName: '1月', totalOutput: 5000000, distributed: 3500000 },
  { id: 2, year: 2023, month: 2, monthName: '2月', totalOutput: 8000000, distributed: 6000000 },
  { id: 3, year: 2023, month: 3, monthName: '3月', totalOutput: 12000000, distributed: 9000000 },
  { id: 4, year: 2023, month: 4, monthName: '4月', totalOutput: 10000000, distributed: 7500000 },
  { id: 5, year: 2023, month: 5, monthName: '5月', totalOutput: 9500000, distributed: 7000000 },
  { id: 6, year: 2023, month: 6, monthName: '6月', totalOutput: 11000000, distributed: 8000000 },
];

const projectOptions = [
  { value: 'all', label: '全部项目' },
  { value: 'P001', label: '凯泽利总部大楼' },
  { value: 'P002', label: '未来科技园' },
  { value: 'P003', label: '城市综合体' },
];

export default function OutputReports() {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState([]);
  const [chartType, setChartType] = useState('column');
  const [projectFilter, setProjectFilter] = useState('all');
  
  const columns = [
    {
      title: '年份',
      dataIndex: 'year',
      key: 'year',
      width: 100,
    },
    {
      title: '月份',
      dataIndex: 'monthName',
      key: 'month',
      width: 100,
    },
    {
      title: '总产值(元)',
      dataIndex: 'totalOutput',
      key: 'totalOutput',
      render: value => value.toLocaleString(),
      sorter: (a, b) => a.totalOutput - b.totalOutput,
    },
    {
      title: '已分配产值(元)',
      dataIndex: 'distributed',
      key: 'distributed',
      render: value => value.toLocaleString(),
      sorter: (a, b) => a.distributed - b.distributed,
    },
    {
      title: '分配比例',
      key: 'ratio',
      render: (_, record) => `${Math.round((record.distributed / record.totalOutput) * 100)}%`,
      sorter: (a, b) => (a.distributed / a.totalOutput) - (b.distributed / b.totalOutput),
    },
  ];

  const handleSearch = () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  // 柱状图配置
  const columnConfig = {
    data: reportData,
    xField: 'monthName',
    yField: 'totalOutput',
    seriesField: 'type',
    isGroup: true,
    color: ['#1890ff', '#52c41a'],
    meta: {
      totalOutput: {
        alias: '总产值',
        formatter: (v) => `${(v / 10000).toFixed(2)}万`,
      },
      distributed: {
        alias: '已分配产值',
        formatter: (v) => `${(v / 10000).toFixed(2)}万`,
      },
    },
    legend: {
      position: 'top',
    },
    tooltip: {
      formatter: (datum) => ({
        name: datum.type === 'totalOutput' ? '总产值' : '已分配产值',
        value: `${(datum.value / 10000).toFixed(2)}万`,
      }),
    },
    yAxis: {
      label: {
        formatter: (v) => `${(v / 10000).toFixed(0)}万`,
      },
    },
    series: [
      {
        name: '总产值',
        type: 'totalOutput',
      },
      {
        name: '已分配产值',
        type: 'distributed',
      },
    ],
  };

  // 饼图配置
  const pieConfig = {
    data: reportData.map(item => ({
      type: item.monthName,
      value: item.totalOutput,
      distributed: item.distributed,
    })),
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'element-active' }],
    tooltip: {
      formatter: (datum) => {
        return {
          name: datum.type,
          value: `${(datum.value / 10000).toFixed(2)}万 (${Math.round((datum.distributed / datum.value) * 100)}%)`,
        };
      },
    },
  };

  // 折线图配置
  const lineConfig = {
    data: reportData,
    xField: 'monthName',
    yField: 'totalOutput',
    seriesField: 'type',
    color: ['#1890ff', '#52c41a'],
    yAxis: {
      label: {
        formatter: (v) => `${(v / 10000).toFixed(0)}万`,
      },
    },
    meta: {
      totalOutput: {
        alias: '总产值',
      },
      distributed: {
        alias: '已分配产值',
      },
    },
    tooltip: {
      formatter: (datum) => ({
        name: datum.type === 'totalOutput' ? '总产值' : '已分配产值',
        value: `${(datum.value / 10000).toFixed(2)}万`,
      }),
    },
    series: [
      {
        name: '总产值',
        type: 'totalOutput',
      },
      {
        name: '已分配产值',
        type: 'distributed',
      },
    ],
  };

  // 统计数据
  const totalStats = {
    totalOutput: reportData.reduce((sum, item) => sum + item.totalOutput, 0),
    distributed: reportData.reduce((sum, item) => sum + item.distributed, 0),
    ratio: Math.round(
      (reportData.reduce((sum, item) => sum + item.distributed, 0) / 
       reportData.reduce((sum, item) => sum + item.totalOutput, 0)) * 100
    ),
  };

  const renderChart = () => {
    switch (chartType) {
      case 'column':
        return (
          <Column 
            {...columnConfig}
            data={reportData.map(item => ({
              monthName: item.monthName,
              totalOutput: item.totalOutput,
              distributed: item.distributed,
              type: '总产值',
            })).concat(reportData.map(item => ({
              monthName: item.monthName,
              totalOutput: item.distributed,
              distributed: item.distributed,
              type: '已分配产值',
            })))}
          />
        );
      case 'pie':
        return <Pie {...pieConfig} />;
      case 'line':
        return (
          <Line 
            {...lineConfig}
            data={reportData.map(item => ({
              monthName: item.monthName,
              totalOutput: item.totalOutput,
              distributed: item.distributed,
              type: '总产值',
            })).concat(reportData.map(item => ({
              monthName: item.monthName,
              totalOutput: item.distributed,
              distributed: item.distributed,
              type: '已分配产值',
            })))}
          />
        );
      default:
        return <Column {...columnConfig} />;
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Card 
        title="产值报表" 
        bordered={false}
        extra={
          <Space>
            <Select
              style={{ width: 150 }}
              value={projectFilter}
              onChange={setProjectFilter}
              options={projectOptions}
            />
            <RangePicker 
              style={{ width: 250 }} 
              onChange={setTimeRange} 
              placeholder={['开始时间', '结束时间']}
            />
            <Button type="primary" onClick={handleSearch} loading={loading}>
              查询
            </Button>
          </Space>
        }
      >
        <Space style={{ marginBottom: 16 }}>
          <Button 
            type={chartType === 'column' ? 'primary' : 'default'}
            icon={<BarChartOutlined />}
            onClick={() => setChartType('column')}
          >
            柱状图
          </Button>
          <Button 
            type={chartType === 'pie' ? 'primary' : 'default'}
            icon={<PieChartOutlined />}
            onClick={() => setChartType('pie')}
          >
            饼图
          </Button>
          <Button 
            type={chartType === 'line' ? 'primary' : 'default'}
            icon={<LineChartOutlined />}
            onClick={() => setChartType('line')}
          >
            折线图
          </Button>
          <Button icon={<FileExcelOutlined />}>导出Excel</Button>
          <Button icon={<FilePdfOutlined />}>导出PDF</Button>
        </Space>
        
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={8}>
            <Card>
              <Statistic 
                title="总产值" 
                value={totalStats.totalOutput} 
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#1890ff' }}
                suffix={`(${reportData.length}个月)`}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic 
                title="已分配产值" 
                value={totalStats.distributed} 
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic 
                title="平均分配比例" 
                value={totalStats.ratio} 
                precision={0}
                suffix="%"
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
        </Row>
        
        <Card 
          title={`产值趋势图 (${chartType === 'column' ? '柱状图' : chartType === 'pie' ? '饼图' : '折线图'})`} 
          bordered={false}
          style={{ marginBottom: 24 }}
        >
          <div style={{ height: 400 }}>
            {renderChart()}
          </div>
        </Card>
        
        <Table 
          columns={columns} 
          dataSource={reportData} 
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 800 }}
        />
      </Card>
    </div>
  );
}